<template>
  <div class="generated-stories-view">
    <div class="header">
      <button @click="goBack" class="back-btn">
        <span class="icon">&#8592;</span> 返回
      </button>
      <h2>📚 已生成故事</h2>
      <div class="actions">
        <button @click="refreshStories" class="refresh-btn" :disabled="loading">
          <span class="icon">🔄</span> 刷新
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <span class="spinner"></span> 加载中...
    </div>

    <!-- 故事列表 -->
    <div v-else-if="stories.length > 0" class="stories-container">
      <div 
        v-for="story in stories" 
        :key="story.id" 
        class="story-card"
        @click="openStory(story)"
      >
        <div class="story-header">
          <h3 class="story-title">{{ story.title }}</h3>
          <span class="story-date">{{ formatDate(story.createdAt) }}</span>
        </div>
        
        <div class="story-info">
          <div class="keywords">
            <span class="label">关键词：</span>
            <span 
              v-for="(keyword, index) in story.wordList" 
              :key="index" 
              class="keyword-tag"
            >
              {{ keyword }}
            </span>
          </div>
          
          <div class="story-preview">
            <span class="label">内容预览：</span>
            <p class="preview-text">{{ getPreviewText(story.firstPageContent) }}</p>
          </div>
          
          <div class="story-meta">
            <span class="difficulty">{{ getDifficultyText(story.difficultyLevel) }}</span>
            <span class="theme">{{ getThemeText(story.theme) }}</span>
            <span class="pages">共 {{ story.totalPages }} 页</span>
          </div>
        </div>
        
        <div class="story-actions">
          <button @click.stop="openStory(story)" class="enter-btn">
            进入故事
          </button>
          <button @click.stop="deleteStory(story)" class="delete-btn">
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <div class="empty-icon">📖</div>
      <h3>暂无生成的故事</h3>
      <p>您还没有生成任何故事，快去创建您的第一个故事吧！</p>
      <button @click="goToStoryGeneration" class="create-btn">
        创建故事
      </button>
    </div>

    <!-- 删除确认对话框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click="cancelDelete">
      <div class="modal" @click.stop>
        <h3>确认删除</h3>
        <p>确定要删除故事"{{ deletingStory?.title }}"吗？此操作不可恢复。</p>
        <div class="modal-actions">
          <button @click="cancelDelete" class="cancel-btn">取消</button>
          <button @click="confirmDelete" class="confirm-btn">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request.js";

export default {
  name: "GeneratedStories",
  data() {
    return {
      stories: [],
      loading: false,
      showDeleteConfirm: false,
      deletingStory: null
    };
  },
  created() {
    this.loadStories();
  },
  methods: {
    async loadStories() {
      this.loading = true;
      try {
        let userJson = localStorage.getItem("user");
        let user = JSON.parse(userJson);
        
        const response = await request.get("/api/story/user-stories", {
          params: { userID: user.userID }
        });
        
        if (response && response.stories) {
          this.stories = response.stories;
        } else {
          this.stories = [];
        }
      } catch (error) {
        console.error("加载故事列表失败:", error);
        this.$message.error("加载故事列表失败，请重试");
        this.stories = [];
      } finally {
        this.loading = false;
      }
    },
    
    refreshStories() {
      this.loadStories();
    },
    
    openStory(story) {
      // 跳转到快速故事阅读界面，并传递模板ID
      this.$router.push({
        path: '/fast-story',
        query: { templateId: story.id }
      });
    },
    
    deleteStory(story) {
      this.deletingStory = story;
      this.showDeleteConfirm = true;
    },
    
    cancelDelete() {
      this.showDeleteConfirm = false;
      this.deletingStory = null;
    },
    
    async confirmDelete() {
      if (!this.deletingStory) return;
      
      try {
        let userJson = localStorage.getItem("user");
        let user = JSON.parse(userJson);
        
        await request.delete("/api/story/delete", {
          params: { 
            userID: user.userID,
            templateId: this.deletingStory.id 
          }
        });
        
        this.$message.success("故事删除成功");
        this.loadStories(); // 重新加载列表
        
      } catch (error) {
        console.error("删除故事失败:", error);
        this.$message.error("删除故事失败，请重试");
      } finally {
        this.cancelDelete();
      }
    },
    
    goBack() {
      this.$router.back();
    },
    
    goToStoryGeneration() {
      this.$router.push('/story');
    },
    
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      });
    },
    
    getDifficultyText(level) {
      const difficultyMap = {
        'beginner': '初级',
        'intermediate': '中级',
        'advanced': '高级'
      };
      return difficultyMap[level] || level;
    },
    
    getThemeText(theme) {
      const themeMap = {
        'adventure': '冒险',
        'mystery': '悬疑',
        'fantasy': '奇幻',
        'romance': '浪漫',
        'sci-fi': '科幻'
      };
      return themeMap[theme] || theme;
    },
    
    getPreviewText(content) {
      if (!content) return '暂无预览';
      // 提取前100个字符作为预览
      const text = content.replace(/\*/g, '').trim();
      return text.length > 100 ? text.substring(0, 100) + '...' : text;
    }
  }
};
</script>

<style scoped>
.generated-stories-view {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #e1e8ed;
}

.back-btn, .refresh-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: white;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.back-btn:hover, .refresh-btn:hover {
  background: #f5f5f5;
  border-color: #bbb;
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

h2 {
  margin: 0;
  color: #333;
  font-size: 28px;
  font-weight: 600;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  font-size: 16px;
  color: #666;
}

.spinner {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.stories-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.story-card {
  background: white;
  border: 1px solid #e1e8ed;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.story-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  border-color: #3498db;
}

.story-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.story-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  flex: 1;
  margin-right: 10px;
}

.story-date {
  font-size: 12px;
  color: #888;
  white-space: nowrap;
}

.story-info {
  margin-bottom: 15px;
}

.keywords {
  margin-bottom: 12px;
}

.label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.keyword-tag {
  display: inline-block;
  background: #e3f2fd;
  color: #1976d2;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin: 2px 4px 2px 0;
}

.story-preview {
  margin-bottom: 12px;
}

.preview-text {
  margin: 5px 0 0 0;
  font-size: 14px;
  color: #555;
  line-height: 1.4;
}

.story-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #888;
}

.difficulty, .theme, .pages {
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
}

.story-actions {
  display: flex;
  gap: 10px;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.enter-btn, .delete-btn {
  flex: 1;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.enter-btn {
  background: #3498db;
  color: white;
}

.enter-btn:hover {
  background: #2980b9;
}

.delete-btn {
  background: #e74c3c;
  color: white;
}

.delete-btn:hover {
  background: #c0392b;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #666;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-state h3 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
}

.empty-state p {
  margin: 0 0 30px 0;
  font-size: 16px;
  line-height: 1.5;
}

.create-btn {
  background: #27ae60;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.create-btn:hover {
  background: #229954;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  padding: 30px;
  border-radius: 12px;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}

.modal h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.modal p {
  margin: 0 0 25px 0;
  color: #666;
  line-height: 1.5;
}

.modal-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.cancel-btn, .confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.cancel-btn {
  background: #f8f9fa;
  color: #333;
}

.confirm-btn {
  background: #e74c3c;
  color: white;
}

.cancel-btn:hover {
  background: #e9ecef;
}

.confirm-btn:hover {
  background: #c0392b;
}

@media (max-width: 768px) {
  .generated-stories-view {
    padding: 15px;
  }
  
  .header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .stories-container {
    grid-template-columns: 1fr;
  }
  
  .story-header {
    flex-direction: column;
    gap: 8px;
  }
  
  .story-meta {
    flex-direction: column;
    gap: 5px;
  }
}
</style>